<template>
  <div class="page-container">
    <!--表格内容栏-->
    <cm-table
      ref="dataTable"
      pkName="id"
      :filters="filters"
      :filterFields="filterFields"
      :columns="columns"
      @handleTableOperator="handleTableOperator"
      @handleCellOperator="handleCellOperator"
    />

    <!--新增/编辑/查看界面-->
    <el-dialog
      width="950px"
      v-model="dialogVisible"
      :title="dialogTitle"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <el-form
        :model="formData"
        ref="dataForm"
        label-width="120px"
        label-position="right"
        :disabled="!dialogEdit"
        :rules="rules" 
        :hide-required-asterisk="!dialogEdit"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="formData.username"
                :disabled="formData.button.buttonType === 'approve'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dialogEdit && formData.button.buttonType !== 'approve'">
            <el-form-item
              label="密码"
              :prop="formData.id ? '' : 'password'"
            >
              <el-input
                v-model="formData.password"
                type="password"
                autocomplete="new-password"
                :placeholder="formData.id ? '为空时不修改密码' : ''"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="formData.mobile"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="formData.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否有效" prop="valid">
              <cm-radio v-model="formData.valid" dic-code="dicValid"></cm-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核状态" prop="approveStatus">
              <cm-select v-model="formData.approveStatus" dic-code="dicMemberApproveStatus" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.approveStatus === '2'">
          <el-col :span="24">
            <el-form-item label="审核结果" prop="approveResult">
              <el-input v-model="formData.approveResult" type="textarea" :rows="5"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="可操作账号">
              <el-table
                ref="formDataTable"
                class="edit-table"
                width="100%"
                border
                :data="formData.accountList"
              >
                <el-table-column
                  v-if="dialogEdit"
                  type="selection"
                  align="center"
                  header-align="center"
                />
                <el-table-column
                  header-align="center"
                  align="center"
                  label="券商名称"
                  min-width="120"
                  prop="brokerName"
                />
                <el-table-column
                  header-align="center"
                  align="center"
                  label="资金账号"
                  width="120"
                  prop="account"
                />
                <el-table-column
                  header-align="center"
                  label="基准金额"
                  width="100"
                >
                  <template #header>
                    <el-tooltip>
                      <template #content>
                        <div>
                          <div>用于计算可下单的金额</div>
                        </div>
                      </template>
                      <span>
                          <span style="margin-right: 5px">基准金额</span>
                          <span><i class="fa fa-question-circle-o" /></span>
                        </span>
                    </el-tooltip>
                  </template>
                  <template v-slot="scope">
                    <cm-number v-model="scope.row.baseMoney" :point="2"/>
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  label="可用金额"
                  width="100"
                >
                  <template v-slot="scope">
                    <cm-number v-model="scope.row.availableMoney" :point="2"/>
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  label="手续费率"
                  width="100"
                >
                  <template v-slot="scope">
                    <cm-number v-model="scope.row.chargeRate" :point="4"/>
                  </template>
                </el-table-column>
                <el-table-column
                  header-align="center"
                  label="最低手续费"
                  width="100"
                >
                  <template v-slot="scope">
                    <cm-number v-model="scope.row.chargeLowest" :point="2"/>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updateTime">
              <el-input v-model="formData.updateTime"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-input v-model="formData.createTime"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button 
          v-if="dialogEdit"
          size="large"
          type="info"
          @click="dialogVisible=false"
        >取消</el-button>
        <el-button 
          v-if="dialogEdit"
          size="large"
          type="primary"
          @click.native="submitForm" 
          :loading="editLoading"
        >提交</el-button>
        <el-button 
          v-if="!dialogEdit"
          size="large"
          type="info"
          @click="dialogVisible=false"
        >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, nextTick, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import api from '@/http/api';
import tool from "@/utils/tool";

const filters = ref({
  username: ''
});
      // 分页查询条件
const filterFields = ref([
  {prop: "username", label: "用户名"}
]);

// 分页列表字段
const columns = ref([
  {prop: "username", label: "用户名", width: 160, click: true},
  {prop: "mobile", label: "手机号码", width: 160},
  {prop: "email", label: "电子邮箱", width: 200},
  {prop: "valid", label: "是否有效", type: 'select', dicCode: 'dicValid', width: 100},
  {prop: "approveStatus", label: "审核状态", type: 'select', dicCode: 'dicMemberApproveStatus', width: 100},
  {prop: "approveResult", label: "审核结果", minWidth: 120},
  {prop: "registerTime", label: "注册时间", width: 160},
  {prop: "updateTime", label: "更新时间", width: 160},
  {prop: "createTime", label: "创建时间", width: 160},
]);

// 表单数据验证规则
const rules = ref({
  username: [
    {required: true, message: '请输入用户名', trigger: 'change'},
    {max: 20, message: '长度必须小于等于 20 个字符！', trigger: 'change'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'change'},
    {max: 100, message: '长度必须小于等于 100 个字符！', trigger: 'change'}
  ],
  mobile: [
    {max: 20, message: '长度必须小于等于 20 个字符！', trigger: 'change'}
  ],
  email: [
    {max: 50, message: '长度必须小于等于 50 个字符！', trigger: 'change'}
  ],
  valid: [
    {required: true, message: '请选择是否有效', trigger: 'change'},
    {max: 1, message: '长度必须小于等于 1 个字符！', trigger: 'change'}
  ],
  approveStatus: [
    {required: true, message: '请选择审核状态', trigger: 'change'},
    {max: 2, message: '长度必须小于等于 2 个字符！', trigger: 'change'}
  ],
  approveResult: [
    {required: true, message: '请输入审核结果', trigger: 'change'},
    {max: 500, message: '长度必须小于等于 500 个字符！', trigger: 'change'}
  ],
  registerTime: [
    {required: true, message: '请输入注册时间', trigger: 'change'}
  ],
});

const dataTable = ref(); // 弹窗表单数据
const formDataTable = ref(); // 弹窗表单数据
const dataForm = ref(); // 弹窗表单数据
const formData = ref({}); // 弹窗表单数据
const dialogTitle = ref(''); // 新增/编辑/查看弹窗标题
const dialogVisible = ref(false); // 弹窗是否显示
const editLoading = ref(false); // 弹窗表单提交状态
const dialogEdit = ref(false); // 弹窗是否编辑
const accountList = ref([]);

const handleCellOperator = (property, value, row) => {
  api.post('/member/queryBy', {id: row.id}).then(res => {
    formData.value = Object.assign({}, res.data || {}, {button: {}});
    dialogVisible.value = true;
    dialogEdit.value = false;
    dialogTitle.value = "查看";

    nextTick(() => {
      dataForm.value && dataForm.value.clearValidate();
    });
  });
};

// 显示操作界面
const handleTableOperator = (button, row) => {
  dialogEdit.value = true;
  dialogTitle.value = button.name;

  if (button.buttonType === 'edit' || button.buttonType === 'approve') {
    api.post('/member/queryBy', {id: row.id}).then(res => {
      let brokerAccountList = res.data && res.data.accountList || [];
      let resultList = [];
      brokerAccountList.forEach(item => resultList.push(item));

      accountList.value.forEach(account => {
        if(!brokerAccountList.some(item => item.brokerAccountId === account.id)) {
          resultList.push({
            brokerAccountId: account.id,
            brokerId: account.brokerId,
            brokerName: account.brokerName,
            account: account.account
          });
        }
      });

      formData.value = Object.assign({}, res.data || {}, {accountList: resultList, button: button});
      dialogVisible.value = true;

      nextTick(() => {
        resultList.filter(item => item.id).forEach(row => {
          formDataTable.value && formDataTable.value.toggleRowSelection(row);
        });
        dataForm.value && dataForm.value.clearValidate();
      });
    });
  } else {
    let resultList = [];
    accountList.value.forEach(account => {
      resultList.push({
        brokerAccountId: account.id,
        brokerId: account.brokerId,
        brokerName: account.brokerName,
        account: account.account
      });
    });
    formData.value = {valid: '1', approveStatus: '1', accountList: resultList, button: button};
    dialogVisible.value = true;
    nextTick(() => {
      dataForm.value && dataForm.value.clearValidate();
    });
  }
};

// 表单提交
const submitForm = () => {
  let accountList = formDataTable.value.getSelectionRows() || [];
  for (let account of accountList) {
    if (!account.baseMoney || account.baseMoney <= 0) {
      ElMessage.error("基准金额必须大于0！");
      return;
    }
    if (!account.availableMoney || account.availableMoney <= 0) {
      ElMessage.error("可用金额必须大于0！");
      return;
    }
    if (account.chargeRate == null || account.chargeRate === '' || account.chargeRate < 0 || account.chargeRate >= 1) {
      ElMessage.error("手续费率必须大于0，小于1！");
      return;
    }
    if (account.chargeLowest == null || account.chargeLowest === '' || account.chargeLowest < 0) {
      ElMessage.error("最低手续费大于0！");
      return;
    }
  }

  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true;
        let data = tool.deepClone(formData.value);
        data.button = null;
        data.accountList = accountList;
        api.post(formData.value.button.dataDestUrl, data).then(res => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          dataTable.value.findPage();
          editLoading.value = false;
        }).catch(() => {
          editLoading.value = false;
        })
      });
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  })
};

const loadAccountList = async () => {
  await api.post("/brokerAccount/queryList", {}).then(res => {
    accountList.value = res.data || [];
  })
}

onMounted(() => {
  loadAccountList();
});
</script>